package com.hengxinguotong.zhihuichengjian.ui.engineering.task;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.AualityTestAddPicAdapter;
import com.hengxinguotong.zhihuichengjian.adapter.SubmitTaskAdapter;
import com.hengxinguotong.zhihuichengjian.bean.Structure;
import com.hengxinguotong.zhihuichengjian.bean.StructureListRes;
import com.hengxinguotong.zhihuichengjian.bean.StructureRes;
import com.hengxinguotong.zhihuichengjian.bean.Task;
import com.hengxinguotong.zhihuichengjian.bean.TaskRecordListRes;
import com.hengxinguotong.zhihuichengjian.bean.TaskRecordListRes.TaskRecord;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.utils.FileUtil;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXEditTextView;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.view.MyStructureTreeView;
import com.lidroid.xutils.http.RequestParams;
import com.orhanobut.logger.Logger;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * 提交任务
 * Created by liux on 2017/3/27.
 */

public class SubmitTaskActivity extends BaseActivity implements AualityTestAddPicAdapter.OnRecyclerViewClickListener {
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.title_tv)
    HXTextView titleTv;
    @BindView(R.id.save_tv)
    HXTextView saveTv;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.task_lv)
    ListView taskLv;

    private SubmitTaskAdapter submitTaskAdapter;
    private AualityTestAddPicAdapter aualityTestAddPicAdapter;
    private List<String> paths;
    private List<String> minPaths;
    private ViewHolder viewHolder;
    private Task task;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_submit_task);
        ButterKnife.bind(this);
        task = (Task) getIntent().getSerializableExtra("task");
        View header = View.inflate(this, R.layout.submit_task_head, null);
        viewHolder = new ViewHolder(header);
        taskLv.addHeaderView(header);
        initView();
        submitTaskAdapter = new SubmitTaskAdapter(this, new ArrayList<TaskRecord>());
        taskLv.setAdapter(submitTaskAdapter);
        if (task != null) {
            if ("1".equals(task.getStatus())) {
                titleTv.setText("待受理详情");
            } else if ("2".equals(task.getStatus())) {
                titleTv.setText("处理中详情");
            } else if ("3".equals(task.getStatus())) {
                titleTv.setText("待检查详情");
            } else if ("4".equals(task.getStatus())) {
                titleTv.setText("检查不通过详情");
            } else if ("5".equals(task.getStatus())) {
                titleTv.setText("已完成详情");
            }
            getcTaskInfo();
        }
    }

    private void initView() {
        viewHolder.infoRl.setOnClickListener(this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        viewHolder.addPicRv.setLayoutManager(linearLayoutManager);
        paths = new ArrayList<String>();
        paths.add(Utils.ADDPIC);
        aualityTestAddPicAdapter = new AualityTestAddPicAdapter(this, paths, this, true);
        viewHolder.addPicRv.setAdapter(aualityTestAddPicAdapter);
        if(null != task.getTeamName()){
            viewHolder.teamRl.setVisibility(View.VISIBLE);
            viewHolder.teamTv.setText(task.getTeamName());
        }
        viewHolder.stateTv.setText(getState(task.getStatus()));
        viewHolder.orderNoTv.setText(task.getOrderNo());
        viewHolder.structureTv.setText(task.getScheduledPlanName());
        listStructureTree();
//        viewHolder.unitTv.setText(task.getProjectQuantityUnit());
//        viewHolder.quantityTv.setText(task.getProjectQuantityEstimate());
        viewHolder.companyTv.setText(task.getProjectCompanyName());
        viewHolder.processingPeopleTv.setText(task.getProcessorName());
        viewHolder.processingPeopleMoblie.setText(task.getProcessorMobile());
        viewHolder.examinerTv.setText(task.getInspectName());
        viewHolder.taskDescriptionTv.setText(task.getRemark());
        if ("1".equals(task.getStatus())) {
            if (SPUtil.getString(this, "userId").equals(task.getProcessorId())) {
                saveTv.setVisibility(View.VISIBLE);
                viewHolder.resultTitle.setVisibility(View.GONE);
                viewHolder.resultLl.setVisibility(View.GONE);
                saveTv.setText("确认");
            } else {
                viewHolder.editLl.setVisibility(View.GONE);
                saveTv.setVisibility(View.GONE);
            }
        } else if ("2".equals(task.getStatus()) || "4".equals(task.getStatus())) {
            if (SPUtil.getString(this, "userId").equals(task.getProcessorId())) {
                saveTv.setVisibility(View.VISIBLE);
                viewHolder.resultTitle.setVisibility(View.GONE);
                viewHolder.resultLl.setVisibility(View.GONE);
                saveTv.setText("提交");
            } else {
                viewHolder.editLl.setVisibility(View.GONE);
                saveTv.setVisibility(View.GONE);
            }
        } else if ("3".equals(task.getStatus())) {
            Logger.d("userId-----------" + SPUtil.getString(this, "userId"));
            Logger.d("getInspectId-----------" + task.getInspectId());

            if (SPUtil.getString(this, "userId").equals(task.getInspectId())) {
                saveTv.setVisibility(View.VISIBLE);
                saveTv.setText("提交");
            } else {
                viewHolder.editLl.setVisibility(View.GONE);
                saveTv.setVisibility(View.GONE);
            }
        } else if ("5".equals(task.getStatus())) {
            viewHolder.editLl.setVisibility(View.GONE);
            saveTv.setVisibility(View.GONE);
        }

    }

    @OnClick({R.id.iv_back, R.id.save_tv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.save_tv:
                getMinImage();
                break;
            case R.id.info_rl:
                if(viewHolder.infoLl.isShown()){
                    viewHolder.infoLl.setVisibility(View.GONE);
                    viewHolder.infoTv.setText("基本信息（信息已折叠，点击展开）");
                }else{
                    viewHolder.infoLl.setVisibility(View.VISIBLE);
                    viewHolder.infoTv.setText("基本信息（信息已展开，点击折叠）");
                }
                break;
        }
    }


    @Override
    public void onItemClick(View v, int position) {
        Intent intent;
        if (paths.get(position).equals(Utils.ADDPIC)) {
            List<String> tempStrings = new ArrayList<String>();
            tempStrings.addAll(paths);
            tempStrings.remove(tempStrings.size() - 1);
            MultiImageSelector.create()
                    .showCamera(true) // show camera or not. true by default_grey
                    .count(9) // max select image size, 9 by default_grey. used width #.multi()
                    .multi()
                    .origin((ArrayList<String>) tempStrings)
                    .start(this, 1);
        } else {
            paths.remove(position);
            aualityTestAddPicAdapter.notifyDataSetChanged();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && data != null) {
            paths = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
            paths.add(Utils.ADDPIC);
            if (aualityTestAddPicAdapter != null) {
                aualityTestAddPicAdapter.setPaths(paths);
            }
        }
    }


    private String getState(String state) {
        if ("1".equals(state)) {
            return "待受理";
        }

        if ("2".equals(state)) {
            return "处理中";
        }

        if ("3".equals(state)) {
            return "待检查";
        }

        if ("4".equals(state)) {
            return "检查不通过";
        }

        if ("5".equals(state)) {
            return "已完成";
        }

        return "已完成";

    }


    private void getMinImage() {

        if (paths.size() > 1) {
            Utils.startDownload(getResources().getString(R.string.loading), this);

            new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... voids) {
                    minPaths = new ArrayList<String>();
                    for (int i = 0; i < paths.size() - 1; i++) {
                        String path = FileUtil.imageDir1 + System.currentTimeMillis() + ".jpg";
                        FileUtil.writeByteArrayToPath(path, FileUtil.handleUploadImg(paths.get(i)));
                        minPaths.add(path);
                    }
                    return null;
                }


                @Override
                protected void onPostExecute(Void aVoid) {
                    submitTask();
                }


            }.execute();
        } else {
            minPaths = new ArrayList<String>();
            submitTask();
        }

    }

    private void getcTaskInfo() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("taskId", task.getTaskId());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(null, this, "/taskDistribution/queryListDetial/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    TaskRecordListRes taskRecordListRes = gson.fromJson(json, TaskRecordListRes.class);
                    submitTaskAdapter = new SubmitTaskAdapter(SubmitTaskActivity.this, taskRecordListRes.getValue());
                    taskLv.setAdapter(submitTaskAdapter);
                }
            }

            @Override
            public void onFailure(String json) {
            }
        });
    }


    private void submitTask() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("taskId", task.getTaskId());

        for (int i = 0; i < minPaths.size(); i++) {
            params.addBodyParameter("files[" + i + "]", new File(minPaths.get(i)));
        }

        params.addBodyParameter("personId", SPUtil.getString(this, "userId"));

        if ("1".equals(task.getStatus())) {
            params.addBodyParameter("taskStatus", "2");
        } else if ("2".equals(task.getStatus()) || "4".equals(task.getStatus())) {
            params.addBodyParameter("taskStatus", "3");
        } else if ("3".equals(task.getStatus())) {
            if (viewHolder.resultRg.getCheckedRadioButtonId() == -1) {
                showToast("请选择处理结果");
                return;
            }

            if (viewHolder.resultRg.getCheckedRadioButtonId() == R.id.pass) {
                params.addBodyParameter("taskStatus", "5");
            } else {
                params.addBodyParameter("taskStatus", "4");
            }
        }
        params.addBodyParameter("remark", viewHolder.remarksEtv.getEditableText().toString());

        Utils.requestData(getResources().getString(R.string.loading), this, "/taskDistribution/insetTaskProces/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                showToast("提交成功");
                setResult(TaskListActivity.UPDATE);
                finish();
            }

            @Override
            public void onFailure(String json) {

            }
        });

    }

    private void listStructureTree() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("taskId", task.getTaskId());
            jsonObject.put("constructionId", SPUtil.getString(this, "constructionid"));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(null, this, "/projectStructure/listStructureTree/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    StructureListRes structureRes = gson.fromJson(json, StructureListRes.class);
                    processProjectStructure(structureRes.getValue());
                }
            }

            @Override
            public void onFailure(String json) {
            }
        });
    }

    private void processProjectStructure(List<Structure> structures){
        MyStructureTreeView mySelectTreeView = new MyStructureTreeView(this);
        mySelectTreeView.setDatas(structures);
        viewHolder.structureRl.removeAllViews();
        viewHolder.structureRl.addView(mySelectTreeView);
    }

    class ViewHolder {
        @BindView(R.id.info_rl)
        RelativeLayout infoRl;
        @BindView(R.id.info_tv)
        HXTextView infoTv;
        @BindView(R.id.info_ll)
        LinearLayout infoLl;
        @BindView(R.id.state_tv)
        HXTextView stateTv;
        @BindView(R.id.order_no_tv)
        HXTextView orderNoTv;
        @BindView(R.id.structure_tv)
        HXTextView structureTv;
        @BindView(R.id.structure_rl)
        RelativeLayout structureRl;
        @BindView(R.id.unit_tv)
        HXTextView unitTv;
        @BindView(R.id.quantity_tv)
        HXTextView quantityTv;
        @BindView(R.id.company_tv)
        HXTextView companyTv;
        @BindView(R.id.team_rl)
        RelativeLayout teamRl;
        @BindView(R.id.team_tv)
        HXTextView teamTv;
        @BindView(R.id.processing_people_tv)
        HXTextView processingPeopleTv;
        @BindView(R.id.processing_people_moblie)
        HXTextView processingPeopleMoblie;
        @BindView(R.id.examiner_tv)
        HXTextView examinerTv;
        @BindView(R.id.task_description_tv)
        HXTextView taskDescriptionTv;
        @BindView(R.id.no_pic_tv)
        HXTextView noPicTv;
        @BindView(R.id.add_pic_rv)
        RecyclerView addPicRv;
        @BindView(R.id.remarks_etv)
        HXEditTextView remarksEtv;
        @BindView(R.id.result_title)
        HXTextView resultTitle;
        @BindView(R.id.pass)
        RadioButton pass;
        @BindView(R.id.notpass)
        RadioButton notpass;
        @BindView(R.id.result_rg)
        RadioGroup resultRg;
        @BindView(R.id.result_ll)
        LinearLayout resultLl;
        @BindView(R.id.edit_ll)
        LinearLayout editLl;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
